package com.linkage.jz.bankruptcy.fragment.Vote;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteVotersDetailActivity_Manager;
import com.linkage.jz.bankruptcy.adapter.FileAdapter;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteDetail;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;
import com.linkage.seapeak.activity.vote.EditVoteMemberGroupActivity;
import com.linkage.seapeak.activity.vote.EditVoteMemberNoGroupActivity;
import com.linkage.seapeak.activity.vote.ShowVoteMemberGroupActivity;
import com.linkage.seapeak.activity.vote.ShowVoteMemberNoGroupActivity;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.pojo.VoteGroup;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 表决详情页Tab-表决详情
 */
public class ProVoteDetailFragment_Manager extends ProVoteBaseFragment implements View.OnClickListener {
    public static final String TAG = "ProVoteDetailFragment";
    public static final String ARG_PARAM_ID = "arg_param_id";

    private ProVoteDetail mProVoteDetail;
    private String mID = "";

    private TextView tv_vote_cancel, tv_vote_type, tv_vote_name, tv_vote_content, tv_vote_rule_name,
            tv_vote_rule_explain,
            tv_vote_time_start, tv_vote_time_end, tv_vote_presetTime, tv_vote_time_notice;

    private LinearLayout area_files_tip, area_groups;



    private CommonPromptDialog mPromptDialog;

    private RecyclerView mFileRecyclerView;
    private List<TaskAtta> mFileList = new ArrayList<>();
    private FileAdapter mFileAdapter;

    private RecyclerView mFileRecyclerView_courtHolding;
    private List<TaskAtta> mFileList_courtHolding = new ArrayList<>();
    private FileAdapter mFileAdapter_courtHolding;

    private RecyclerView mImgRecyclerView;
    private List<UploadImage> mImgList = new ArrayList<>();
    private BaseCreateActivity.GridImagesAdapter mImgAdapter;

    private int mJudge = 1;

    public static ProVoteDetailFragment_Manager newInstance(String id) {
        ProVoteDetailFragment_Manager fragment = new ProVoteDetailFragment_Manager();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM_ID, id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mID = getArguments().getString(ARG_PARAM_ID);
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_pro_vote_detail_manager, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        tv_vote_cancel = getView().findViewById(R.id.tv_vote_cancel);
        tv_vote_type = getView().findViewById(R.id.tv_vote_type);
        tv_vote_name = getView().findViewById(R.id.tv_vote_name);
        tv_vote_content = getView().findViewById(R.id.tv_vote_content);
        tv_vote_rule_name = getView().findViewById(R.id.tv_vote_rule_name);
        tv_vote_rule_explain = getView().findViewById(R.id.tv_vote_rule_explain);
        tv_vote_time_start = getView().findViewById(R.id.tv_vote_time_start);
        tv_vote_time_end = getView().findViewById(R.id.tv_vote_time_end);
        tv_vote_presetTime = getView().findViewById(R.id.tv_vote_presetTime);
        tv_vote_time_notice = getView().findViewById(R.id.tv_vote_time_notice);

        area_files_tip = getView().findViewById(R.id.area_files_tip);
        area_groups = getView().findViewById(R.id.area_groups);

        mFileRecyclerView = getView().findViewById(R.id.recycler_files);
        mFileRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mFileAdapter = new FileAdapter(getActivity(), mFileList);
//        mFileAdapter.openLoadAnimation();
        mFileRecyclerView.setAdapter(mFileAdapter);
//        mFileAdapter.setOnItemChildClickListener((adapter, view, position) -> {
//            switch (view.getId()) {
//                case R.id.img_file_type:
//                case R.id.tv_file_name:
//                    BaseActivity.openOrDownloadFile(mFileList.get(position), getActivity());
//                    break;
//            }
//        });

        mFileRecyclerView_courtHolding = getView().findViewById(R.id.recycler_files_courtHolding);
        mFileRecyclerView_courtHolding.setLayoutManager(new LinearLayoutManager(getActivity()));
        mFileAdapter_courtHolding = new FileAdapter(getActivity(), mFileList_courtHolding);
//        mFileAdapter_courtHolding.openLoadAnimation();
        mFileRecyclerView_courtHolding.setAdapter(mFileAdapter_courtHolding);
//        mFileAdapter_courtHolding.setOnItemChildClickListener((adapter, view, position) -> {
//            switch (view.getId()) {
//                case R.id.img_file_type:
//                case R.id.tv_file_name:
//                    BaseActivity.openOrDownloadFile(mFileList_courtHolding.get(position), getActivity());
//                    break;
//            }
//        });

        mImgRecyclerView = getView().findViewById(R.id.recycler_imgs);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL,
                false);
        mImgRecyclerView.setLayoutManager(manager);
        mImgAdapter = new BaseCreateActivity.GridImagesAdapter((BaseCreateActivity) getActivity(),
                BaseCreateActivity.TYPE_EDIT);
        mImgAdapter.setList(mImgList);
        mImgRecyclerView.setAdapter(mImgAdapter);
        ((RadioGroup) getView().findViewById(R.id.rg_vote_courtHolding)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rg_vote_courtHolding_1) {
                    mJudge = 1;
                } else if (checkedId == R.id.rg_vote_courtHolding_2) {
                    mJudge = 2;
                } else {
                    mJudge = 3;
                }
            }
        });

        getView().findViewById(R.id.tv_vote_notice_send).setOnClickListener(this);
        getView().findViewById(R.id.tv_vote_detail_see_voters).setOnClickListener(this);
        getView().findViewById(R.id.btn_courtHolding_upload).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.tv_vote_detail_see_voters:
                if (mProVoteDetail.isGrouped()) {
                    intent = new Intent(getActivity(), ShowVoteMemberGroupActivity.class);
                    intent.putExtra("projectId", mProVoteDetail.getBankruptcyProjectId());
                    intent.putExtra("voteRule", mProVoteDetail.getRule());
                    intent.putExtra("voteId", mProVoteDetail.getId());
                    startActivity(intent);
                } else {
                    intent = new Intent(getActivity(), ShowVoteMemberNoGroupActivity.class);
                    intent.putExtra("projectId", mProVoteDetail.getBankruptcyProjectId());
                    intent.putExtra("voteRule", mProVoteDetail.getRule());
                    intent.putExtra("voteId", mProVoteDetail.getId());
                    startActivity(intent);
                }
//                intent = new Intent(getActivity(), ProVoteVotersDetailActivity_Manager.class);
//                intent.putExtra(ProVoteVotersDetailActivity_Manager.KEY_VOTE, mProVoteDetail);
//                startActivity(intent);
                break;
            case R.id.tv_vote_notice_send:
                mPromptDialog = new CommonPromptDialog(getActivity(), CommonPromptDialog.TYPE_TIPS);
                mPromptDialog.setContent("确认发送通知吗？");
                mPromptDialog.setPositiveClickListener(null, view -> {
                    mPromptDialog.dismiss();
                    sendNotice();
                });
                mPromptDialog.setNegativeClickListener(null, view -> mPromptDialog.dismiss());
                mPromptDialog.show();
                break;

            case R.id.btn_courtHolding_upload:
                if (mImgList.size() == 0) {
                    ToastUtil.showShort("请选择法院裁定文件");
                    return;
                }
                mPromptDialog = new CommonPromptDialog(getActivity(), CommonPromptDialog.TYPE_TIPS);
                mPromptDialog.setContent("确认上传法院裁定文件吗？");
                mPromptDialog.setPositiveClickListener(null, view -> {
                    mPromptDialog.dismiss();
                    uploadCourtFile();
                });
                mPromptDialog.setNegativeClickListener(null, view -> mPromptDialog.dismiss());
                mPromptDialog.show();
                break;
        }
    }


    public void refreshInfo(ProVoteDetail bean) {
        mProVoteDetail = bean;
        LogUtil.v(TAG, this.mProVoteDetail.toString());

        if (mProVoteDetail.getStatus() == ProVote.STATUS_YCX) {
            tv_vote_cancel.setText(mProVoteDetail.getCancel());
            getView().findViewById(R.id.area_cancel).setVisibility(View.VISIBLE);
        }

        tv_vote_type.setText(ProVote.TYPES.get(this.mProVoteDetail.getType()));
        tv_vote_name.setText(this.mProVoteDetail.getTitle());
        tv_vote_content.setText(this.mProVoteDetail.getContent());
        tv_vote_rule_name.setText(this.mProVoteDetail.getRuleName());
        tv_vote_rule_explain.setText(this.mProVoteDetail.getRuleExplain());
        tv_vote_time_start.setText(DateFormatUtils.long2Str(this.mProVoteDetail.getStartTime(), true));
        tv_vote_time_end.setText(DateFormatUtils.long2Str(this.mProVoteDetail.getEndTime(), true));
        tv_vote_presetTime.setText(String.valueOf(this.mProVoteDetail.getPresetTime()));
        if (this.mProVoteDetail.getTimeMode() == 1) {
            tv_vote_time_notice.setText(DateFormatUtils.long2Str(this.mProVoteDetail.getNotificationTime(), true));
        } else {
            tv_vote_time_notice.setText("待定");
        }

        area_groups.removeAllViews();
        if (mProVoteDetail.getGroups() == null) {
            View view = View.inflate(getActivity(), R.layout.fragment_pro_vote_detail_manager_group_item, null);
            TextView tv_group = view.findViewById(R.id.tv_group);
            tv_group.setText("无分组（" + mProVoteDetail.getMemberTotal() + "人）");
            area_groups.addView(view);
        } else {
            for (VoteGroup group : mProVoteDetail.getGroups()) {
                View view = View.inflate(getActivity(), R.layout.fragment_pro_vote_detail_manager_group_item, null);
                TextView tv_group = view.findViewById(R.id.tv_group);
                tv_group.setText(group.getName() + " （" + group.getMemberCount() + "人）");
                area_groups.addView(view);
            }
        }


        if (mProVoteDetail.getFiles() != null && mProVoteDetail.getFiles().size() > 0) {
            area_files_tip.setVisibility(View.GONE);

            mFileList.addAll(mProVoteDetail.getFiles());
            mFileAdapter.notifyDataSetChanged();
        } else {
            area_files_tip.setVisibility(View.VISIBLE);
        }

        // 非结束、通过状态不给上传
        if (mProVoteDetail.getStatus() == ProVote.STATUS_YTG || mProVoteDetail.getStatus() == ProVote.STATUS_WTG) {
            if (mProVoteDetail.isCourtHolding()) {
                mImgAdapter.setEnable(true);
                getView().findViewById(R.id.btn_courtHolding_upload).setVisibility(View.VISIBLE);
                getView().findViewById(R.id.rg_vote_courtHolding).setVisibility(View.VISIBLE);
            } else {
                mImgAdapter.setEnable(false);
                getView().findViewById(R.id.rg_vote_courtHolding).setVisibility(View.GONE);
                getView().findViewById(R.id.btn_courtHolding_upload).setVisibility(View.GONE);
            }

        }else{
            mImgAdapter.setEnable(false);
            getView().findViewById(R.id.rg_vote_courtHolding).setVisibility(View.GONE);
            getView().findViewById(R.id.btn_courtHolding_upload).setVisibility(View.GONE);
        }

//        if (mProVoteDetail.getStatus() == ProVote.STATUS_YJS && mProVoteDetail.getCourtHoldingResult() == 0) {
//
//        }


//        if (mProVoteDetail.getStatus() == ProVote.STATUS_WFC || mProVoteDetail.getStatus() == ProVote.STATUS_WKS || mProVoteDetail.getStatus() == ProVote.STATUS_JXZ) {
//            if (mProVoteDetail.getTimeMode() == 1) {

        if(mProVoteDetail.getCanNotice()) {
            getView().findViewById(R.id.tv_vote_notice_send).setVisibility(View.VISIBLE);
        }else{
            getView().findViewById(R.id.tv_vote_notice_send).setVisibility(View.INVISIBLE);
        }
//            }
//        }

        // 已经上传了裁定文件
        if (mProVoteDetail.getCourtHoldingResult() != 0) {
            getView().findViewById(R.id.btn_courtHolding_upload).setVisibility(View.GONE);
            getView().findViewById(R.id.rg_vote_courtHolding_1).setEnabled(false);
            getView().findViewById(R.id.rg_vote_courtHolding_2).setEnabled(false);
            getView().findViewById(R.id.rg_vote_courtHolding_3).setEnabled(false);
            if (mProVoteDetail.getCourtHoldingResult() == 1) {
                ((RadioButton) getView().findViewById(R.id.rg_vote_courtHolding_1)).setChecked(true);
            } else if (mProVoteDetail.getCourtHoldingResult() == 2) {
                ((RadioButton) getView().findViewById(R.id.rg_vote_courtHolding_2)).setChecked(true);
            } else {
                ((RadioButton) getView().findViewById(R.id.rg_vote_courtHolding_3)).setChecked(true);
            }
            mFileRecyclerView_courtHolding.setVisibility(View.VISIBLE);
            mImgRecyclerView.setVisibility(View.GONE);
            if (mProVoteDetail.getResultFiles() != null) {
                mFileList_courtHolding.addAll(mProVoteDetail.getResultFiles());
                mFileAdapter_courtHolding.notifyDataSetChanged();
            }
        }
    }

    private void sendNotice() {
        showLoading();
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .sendVoteNotice_Manager(userToken, mID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        ToastUtil.showShort("发送成功");
                        getView().findViewById(R.id.tv_vote_notice_send).setVisibility(View.GONE);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                        super.onError(e);
                    }
                });
    }

    private void uploadCourtFile() {
        showLoading();
        JSONArray fileArr = new JSONArray();
        for (int i = 0; i < mImgList.size(); i++) {
            fileArr.put(mImgList.get(i).parse2JSON());
        }
        int  judge= 1;
        if(((RadioButton) getView().findViewById(R.id.rg_vote_courtHolding_1)).isChecked())
        {
            judge = 1;
        }
        if(((RadioButton) getView().findViewById(R.id.rg_vote_courtHolding_2)).isChecked())
        {
            judge = 2;
        }

        if(((RadioButton) getView().findViewById(R.id.rg_vote_courtHolding_3)).isChecked())
        {
            judge = 3;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .uploadCourtFile_Manager(userToken, mProVoteDetail.getId(), mProVoteDetail.getBankruptcyProjectId(),
                        fileArr.toString(), judge)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        ToastUtil.showShort("发送成功");
                        getActivity().finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                        super.onError(e);
                    }
                });
    }

}
